package xm.erzhan.handlers;

import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import xm.erzhan.controllers.ResourceController;
import xm.erzhan.controllers.UserController;
import xm.erzhan.models.ResourceEntity;
import xm.erzhan.models.UserEntity;
import xm.erzhan.models.WarehouseEntity;
import xm.erzhan.models.responseModels.HomeRes;
import xm.erzhan.models.responseModels.NormRes;
import xm.erzhan.repository.ResourceRepository;
import xm.erzhan.utils.Code;
import xm.erzhan.utils.Utils;

import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/home")
public class HomeHandler {

    @Autowired
    private ResourceRepository resourceRepository;

    @Autowired
    private HttpServletRequest request;

    @RequestMapping(value = "/all", method = RequestMethod.GET)
    public @ResponseBody NormRes getHomeAllInfo() throws JSONException {
        NormRes normRes = null;

        normRes = Utils.checkToken(request.getHeader("access-token"));

        int code = normRes.getCode();
        if (code != 200) {
            return normRes;
        }


        // get user info
        String UserName = normRes.getMsg();

        UserController userController = UserController.UserControllerShared();
        UserEntity user = userController.getUserByUserName(UserName);
        if (user == null) {
            normRes = new NormRes(Code.CodeEnum.getCodeByType("USER_NOT_EXIST"), "user info not exist");
            return normRes;
        }


        ResourceController resourceController = ResourceController.resourceControllerShared();

        ResourceEntity resourceEntity = resourceController.getResourceEntitieByPlayerId(1);
        if (resourceEntity == null) {
            resourceEntity = resourceRepository.findByPlayerId(user.getId());
            resourceController.setResourceEntities(resourceEntity);
        }

        // get and check resourceBuildings product status
        resourceController.setAllResourceProduction(resourceEntity);

        resourceRepository.saveAndFlush(resourceEntity);

        HashMap map = new HashMap();
        map.put("resource", resourceEntity);
        normRes = new NormRes(Code.CodeEnum.getCodeByType("OK"), map);

        return normRes;
    }
}
